package com.yylending.las.authority.fingerprint;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.common.fingerprint.FingerprintIdentify;
import com.yyfax.common.fingerprint.base.BaseFingerprint;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.YJKD;
import com.yylending.las.authority.login.LoginActivity;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.Constants;
import com.yylending.las.common.utils.VibratorUtil;

import java.lang.ref.WeakReference;

/**
 * 指纹登录
 * Created by laixj on 2017/7/11.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class FingerprintValidateActivity extends BaseActivity implements View.OnClickListener {

	private final static String TAG = "zhiwenjiesuo";

	@BindView(R.id.fingerprint_validate_message)
	TextView mMessage;
	@BindView(R.id.fingerprint_validate_account)
	TextView mAccount;
	@BindView(R.id.fingerprint_validate_iv)
	ImageView mImageView;
	@BindView(R.id.fingerprint_validate_hint)
	TextView mHint;
	@BindView(R.id.fingerprint_other_account)
	TextView mForget;

	private FingerprintIdentify mFingerprintIdentify;

	private static final int MAX_AVAILABLE_TIMES = 5;
	private boolean mLocked = false;
	private static long mLockedTime = 0L;

	private Handler mCountdownHandler = new CountdownHandler(this);

	public static void start(Activity aty) {
		Intent i = new Intent(aty, FingerprintValidateActivity.class);
		aty.startActivity(i);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!YJKD.getInstance().isFingerprintOpen() || !YJKD.getInstance().hasFingerprint()) {
			Global.LOCKED = false;
			finish();
		}else{
			Global.LOCKED = true;
		}
		CLog.i(TAG, "onResume startValidate");
		startValidate();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_fingerprint_validate);
		ButterKnife.bind(this);
		setTopBarVisible(false);
		initFingerprint();
		initViews();
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	private void initViews() {
		if (!TextUtils.isEmpty(Global.USER_NAME) && !TextUtils.equals(Constants.NO_REAL_VERIFY, Global.USER_NAME)) {
			mAccount.setText(Global.USER_NAME);
		}
	}

	@Override
	public void onBackBtnPressed() {
		return;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		return;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void initFingerprint() {
		mFingerprintIdentify = new FingerprintIdentify(getApplicationContext(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
			@Override
			public void onCatchException(Throwable exception) {
				CLog.i(TAG, "Exception：" + exception.getLocalizedMessage());
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		CLog.i(TAG, "onPause cancelIdentify");
		mFingerprintIdentify.cancelIdentify();
	}

	@Override
	protected void onDestroy() {
		CLog.i(TAG, "onDestroy cancelIdentify");
		mFingerprintIdentify.cancelIdentify();
		super.onDestroy();
	}

	public void startValidate() {
		mMessage.setText(getString(R.string.press_to_fingerprint));
		mFingerprintIdentify.startIdentify(MAX_AVAILABLE_TIMES, mIdentifyListener);
	}

	private BaseFingerprint.FingerprintIdentifyListener mIdentifyListener = new BaseFingerprint.FingerprintIdentifyListener() {
		@Override
		public void onSucceed() {
			CLog.i(TAG, "指纹匹配成功");
			Global.LOCKED = false;
			finish();
		}

		@Override
		public void onNotMatch(int availableTimes) {
			CLog.i(TAG, "指纹匹配失败-availableTimes->" + availableTimes);
			VibratorUtil.vibrate(FingerprintValidateActivity.this, 100);
			mMessage.setText(R.string.fingerprint_not_match);
		}

		@Override
		public void onFailed(boolean isDeviceLocked, int errorCode) {
			CLog.i(TAG, "解锁失败-isDeviceLocked->" + isDeviceLocked + ";errorCode=" + errorCode);
			if (isDeviceLocked) {
				VibratorUtil.vibrate(FingerprintValidateActivity.this, 100);
				if (!mLocked) {
					mLocked = true;
					mLockedTime = System.currentTimeMillis();
				}
				mCountdownHandler.sendMessage(new Message());
			}
		}
	};

	@OnClick({R.id.fingerprint_validate_hint, R.id.fingerprint_other_account, R.id.fingerprint_validate_iv})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.fingerprint_validate_iv:
			case R.id.fingerprint_validate_hint:
				//startValidate();
				break;
			case R.id.fingerprint_other_account:
				LoginActivity.start(this, true);
				break;
		}
	}

	private class CountdownHandler extends Handler {
		WeakReference<FingerprintValidateActivity> weakReference;

		CountdownHandler(FingerprintValidateActivity aty) {
			weakReference = new WeakReference<>(aty);
		}

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			FingerprintValidateActivity aty = weakReference.get();
			if (aty != null) {
				int remain = 30 - new Long((System.currentTimeMillis() - mLockedTime) / 1000).intValue();
				if (remain <= 0) {
					mLocked = false;
					startValidate();
				} else {
					mCountdownHandler.sendMessageDelayed(new Message(), 1000);
					mMessage.setText(getString(R.string.fingerprint_retry_countdown, remain));
				}
			}
		}
	}
}